/**
 * API客户端工具类
 * 提供统一的HTTP请求封装，支持认证、缓存、错误处理
 */
class ApiClient {
    constructor(options = {}) {
        this.baseUrl = options.baseUrl || '';
        this.timeout = options.timeout || 30000;
        this.headers = options.headers || {};
        this.authToken = options.authToken || null;
        this.cacheManager = options.cacheManager || null;
        this.errorHandler = options.errorHandler || null;
        this.debug = options.debug || false;

        // 请求拦截器
        this.requestInterceptors = [];

        // 响应拦截器
        this.responseInterceptors = [];

        // 默认配置
        this.defaultConfig = {
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json',
                ...this.headers
            }
        };
    }

    /**
     * 设置认证令牌
     */
    setAuthToken(token) {
        this.authToken = token;
        if (token) {
            this.defaultConfig.headers['Authorization'] = `Bearer ${token}`;
        } else {
            delete this.defaultConfig.headers['Authorization'];
        }
    }

    /**
     * 设置基础URL
     */
    setBaseUrl(url) {
        this.baseUrl = url.replace(/\/$/, '');
    }

    /**
     * 添加请求拦截器
     */
    addRequestInterceptor(interceptor) {
        this.requestInterceptors.push(interceptor);
        return this;
    }

    /**
     * 添加响应拦截器
     */
    addResponseInterceptor(interceptor) {
        this.responseInterceptors.push(interceptor);
        return this;
    }

    /**
     * 生成完整URL
     */
    buildUrl(endpoint, params = {}) {
        let url = endpoint.startsWith('http') ? endpoint : `${this.baseUrl}${endpoint}`;

        if (Object.keys(params).length > 0) {
            const queryString = new URLSearchParams(params).toString();
            url += `${url.includes('?') ? '&' : '?'}${queryString}`;
        }

        return url;
    }

    /**
     * 应用请求拦截器
     */
    async applyRequestInterceptors(config) {
        let currentConfig = { ...config };

        for (const interceptor of this.requestInterceptors) {
            currentConfig = await interceptor(currentConfig) || currentConfig;
        }

        return currentConfig;
    }

    /**
     * 应用响应拦截器
     */
    async applyResponseInterceptors(response) {
        let currentResponse = response;

        for (const interceptor of this.responseInterceptors) {
            currentResponse = await interceptor(currentResponse) || currentResponse;
        }

        return currentResponse;
    }

    /**
     * 检查缓存
     */
    async checkCache(url, config) {
        if (this.cacheManager && config.useCache) {
            const cacheKey = this.generateCacheKey(url, config);
            const cachedData = await this.cacheManager.get(cacheKey);

            if (cachedData) {
                if (this.debug) {
                    console.log(`[ApiClient] Cache hit for: ${url}`);
                }
                return cachedData;
            }
        }
        return null;
    }

    /**
     * 缓存响应
     */
    async cacheResponse(url, config, data) {
        if (this.cacheManager && config.useCache && config.cacheTTL) {
            const cacheKey = this.generateCacheKey(url, config);
            await this.cacheManager.set(cacheKey, data, config.cacheTTL);

            if (this.debug) {
                console.log(`[ApiClient] Cached response for: ${url}, TTL: ${config.cacheTTL}ms`);
            }
        }
    }

    /**
     * 生成缓存键
     */
    generateCacheKey(url, config) {
        const method = config.method || 'GET';
        const body = config.body ? JSON.stringify(config.body) : '';
        return `${method}:${url}:${body}`;
    }

    /**
     * 执行HTTP请求
     */
    async request(endpoint, options = {}) {
        const config = {
            method: 'GET',
            ...this.defaultConfig,
            ...options,
            headers: {
                ...this.defaultConfig.headers,
                ...options.headers
            }
        };

        // 构建完整URL
        const url = this.buildUrl(endpoint, config.params);

        // 应用请求拦截器
        const processedConfig = await this.applyRequestInterceptors(config);

        // 检查缓存（仅GET请求）
        if (config.method === 'GET') {
            const cachedData = await this.checkCache(url, processedConfig);
            if (cachedData) {
                return cachedData;
            }
        }

        // 设置超时
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), this.timeout);

        try {
            if (this.debug) {
                console.log(`[ApiClient] ${config.method} ${url}`, processedConfig);
            }

            const response = await fetch(url, {
                ...processedConfig,
                signal: controller.signal
            });

            clearTimeout(timeoutId);

            // 处理响应
            let data;
            const contentType = response.headers.get('content-type');

            if (contentType && contentType.includes('application/json')) {
                data = await response.json();
            } else {
                data = await response.text();
            }

            // 标准化响应对象
            const apiResponse = {
                data,
                status: response.status,
                statusText: response.statusText,
                headers: response.headers,
                url: response.url,
                ok: response.ok
            };

            // 应用响应拦截器
            const processedResponse = await this.applyResponseInterceptors(apiResponse);

            // 错误处理
            if (!response.ok) {
                throw this.createError(processedResponse);
            }

            // 缓存成功的GET请求
            if (config.method === 'GET' && response.ok) {
                await this.cacheResponse(url, processedConfig, processedResponse);
            }

            return processedResponse;

        } catch (error) {
            clearTimeout(timeoutId);

            if (error.name === 'AbortError') {
                error = new Error(`请求超时: ${config.timeout}ms`);
                error.code = 'TIMEOUT_ERROR';
            }

            if (this.errorHandler) {
                this.errorHandler.handle(error);
            } else {
                console.error('[ApiClient] Request failed:', error);
            }

            throw error;
        }
    }

    /**
     * 创建标准化错误
     */
    createError(response) {
        const error = new Error(response.data?.message || response.statusText || '请求失败');
        error.code = response.status;
        error.data = response.data;
        error.status = response.status;
        error.response = response;
        return error;
    }

    /**
     * GET请求
     */
    async get(endpoint, params = {}, options = {}) {
        return this.request(endpoint, {
            method: 'GET',
            params,
            ...options
        });
    }

    /**
     * POST请求
     */
    async post(endpoint, data = {}, options = {}) {
        return this.request(endpoint, {
            method: 'POST',
            body: JSON.stringify(data),
            ...options
        });
    }

    /**
     * PUT请求
     */
    async put(endpoint, data = {}, options = {}) {
        return this.request(endpoint, {
            method: 'PUT',
            body: JSON.stringify(data),
            ...options
        });
    }

    /**
     * PATCH请求
     */
    async patch(endpoint, data = {}, options = {}) {
        return this.request(endpoint, {
            method: 'PATCH',
            body: JSON.stringify(data),
            ...options
        });
    }

    /**
     * DELETE请求
     */
    async delete(endpoint, options = {}) {
        return this.request(endpoint, {
            method: 'DELETE',
            ...options
        });
    }

    /**
     * 上传文件
     */
    async upload(endpoint, file, options = {}) {
        const formData = new FormData();
        formData.append('file', file);

        // 添加额外的表单数据
        if (options.formData) {
            Object.entries(options.formData).forEach(([key, value]) => {
                formData.append(key, value);
            });
        }

        return this.request(endpoint, {
            method: 'POST',
            body: formData,
            headers: {}, // 让浏览器自动设置Content-Type
            ...options
        });
    }

    /**
     * 批量请求
     */
    async batch(requests, options = {}) {
        const { parallel = true } = options;

        if (parallel) {
            return Promise.all(requests.map(req => this.request(req.endpoint, req.options)));
        } else {
            const results = [];
            for (const req of requests) {
                results.push(await this.request(req.endpoint, req.options));
            }
            return results;
        }
    }

    /**
     * 分页请求
     */
    async *paginate(endpoint, params = {}, options = {}) {
        const { pageSize = 50, maxPages = 100 } = options;
        let page = 1;
        let hasMore = true;

        while (hasMore && page <= maxPages) {
            const response = await this.get(endpoint, {
                ...params,
                page,
                page_size: pageSize
            }, options);

            yield {
                data: response.data,
                page,
                pageSize,
                response
            };

            // 检查是否还有更多数据
            hasMore = response.data && response.data.length === pageSize;
            page++;
        }
    }

    /**
     * WebSocket连接
     */
    createWebSocket(url, options = {}) {
        const wsUrl = url.startsWith('ws') ? url : `${this.baseUrl.replace('http', 'ws')}${url}`;
        const ws = new WebSocket(wsUrl);

        // 设置认证
        if (this.authToken) {
            ws.addEventListener('open', () => {
                ws.send(JSON.stringify({
                    type: 'auth',
                    token: this.authToken
                }));
            });
        }

        return ws;
    }

    /**
     * 取消所有进行中的请求
     */
    abortAll() {
        // 如果有需要，可以实现请求取消功能
        console.warn('[ApiClient] abortAll() not implemented yet');
    }

    /**
     * 清除缓存
     */
    async clearCache(pattern = null) {
        if (this.cacheManager) {
            await this.cacheManager.clear(pattern);
        }
    }

    /**
     * 获取缓存统计
     */
    async getCacheStats() {
        if (this.cacheManager) {
            return this.cacheManager.getStats();
        }
        return null;
    }
}

// 导出ApiClient
window.ApiClient = ApiClient;